import Vue from 'vue';
import iView from 'iview';
import Util from '../libs/util';
import VueRouter from 'vue-router';
import Cookies from 'js-cookie';
import {routers, otherRouter, appRouter} from './router';

import store from '../store'
Vue.use(VueRouter);

// 路由配置
const RouterConfig = {
  // mode: 'history',
  routes: routers
};

export const router = new VueRouter(RouterConfig);

//路由拦截
router.beforeEach((to, from, next) => {
  iView.LoadingBar.start();
  Util.title(to.meta.title);
  //获取即将访问的路由名称
  const { name } = to;
  const { dispatch } = store;
  //访问登录页面放行
  if(name === 'login') {
    next();
  } else {
    //请求后端判断是否已经登录
    dispatch('online').then((response) => {
      if(response) {
        const { data = {} } = response
        //判断是否锁屏
        if(data.screen === '1' && name !== 'locking') {
          next(false);
          router.replace({
            name: 'locking'
          })
        } else {
          //这里表明已经处于登录状态，则验证访问的当前路由
          const access = to.meta.access
          if(access && access === 1) {
            let permission = store.state.app.currentPermission;
            if(permission.length === 0 && localStorage.permission) {
              permission = JSON.parse(localStorage.permission)
            }
            //需要验证权限
            if (Util.showThisRoute(name, permission)) {
              //有权限，放行
              Util.toDefaultPage([otherRouter, ...appRouter], to.name, router, next);  // 如果在地址栏输入的是一级菜单则默认打开其第一个二级菜单的页面
            } else {
              router.replace({
                name: 'error_401'
              });
              next();
            }
          } else {
            Util.toDefaultPage([otherRouter, ...appRouter], to.name, router, next);
          }
        }
      } else {
        //未登录，如果请求的是登录路由，则放行，否则跳到登录页面
        if(name === 'login') {
          next();
        } else {
          next({
            name: 'login'
          });
        }
      }
    })
  }
})

router.afterEach((to) => {
  Util.openNewPage(router.app, to.name, to.params, to.query);
  iView.LoadingBar.finish();
  window.scrollTo(0, 0);
})
